import {Component, Input, OnInit} from '@angular/core';
import {UtilComponent} from '../../interface/util-component.interface';
import Map from 'ol/Map';
import {fromLonLat} from 'ol/proj';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import {NzMessageService} from 'ng-zorro-antd';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import {Icon, Style} from 'ol/style';


@Component({
    selector: 'kylin-coordinate-position',
    templateUrl: './coordinate-position.component.html',
    styleUrls: ['./coordinate-position.component.less']
})
export class CoordinatePositionComponent implements OnInit, UtilComponent {
    // ---------- 接口实现 begin -------------- //
    hasContent = true;
    map: Map;

    @Input() set data(val) {
        Object.assign(this, val);
    };

    // ---------- 接口实现 end ---------------- //
    lon = '';
    lat = '';
    positionSource: any;
    positionLayer: any;
    redMarker: any;
    blueMarker: any;

    constructor(private message: NzMessageService) {
        this.genMarkerEle();
    }

    genMarkerEle() {
        this.redMarker = new Style({
            image: new Icon(/** @type {module:ol/style/Icon~Options} */ ({
                src: './assets/img/poi-marker_red.png',
                scale: 0.4
            }))
        })
        ;
        this.blueMarker = new Style({
            image: new Icon(/** @type {module:ol/style/Icon~Options} */ ({
                src: './assets/img/poi-marker_blue.png',
                scale: 0.4
            }))
        });
    }

    ngOnInit() {
        this.positionSource = new VectorSource();
        this.positionLayer = new VectorLayer({
            source: this.positionSource,
            style: this.redMarker
        });
    }

    positionByCoord() {
        const center = this.lonLatTransform();
        if (center) {
            const positionFeature = new Feature(new Point(center));
            positionFeature.on('mouseover', () => {
                console.log('tes');
            });
            positionFeature.on('click', () => {
                console.log('tes');
            });
            this.positionSource.addFeature(positionFeature);
            this.map.addLayer(this.positionLayer);
            this.map.getView().animate({center});
        }
    }

    lonLatTransform(): any {
        if (this.lon.trim() && this.lat.trim()) {
            const lon = Number(this.lon.trim());
            const lat = Number(this.lat.trim());
            if (isNaN(lon) && isNaN(lat) || !(lon >= -180 && lon <= 180 && lat >= -90 && lat <= 90)) {
                this.message.warning('请输入正确的经纬度值');
                return false;
            } else {
                return fromLonLat([lon, lat]);
            }
        } else {
            this.message.warning('请输入正确的经纬度值');
        }
    }

    cancel(options?: any): any {
        this.map.removeLayer(this.positionLayer);
    }
}
